package com.edgardeng.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;

/**
 * Mybatis-Plus 新增，修改时默认注入字段
 *
 * @author edgardeng
 * @since 2020-04-28
 */
@Component
public class UpdateRelatedFieldsHandler implements MetaObjectHandler {

        /**
         * 新增操作
         *
         * @param metaObject
         */
        @Override
        public void insertFill(MetaObject metaObject) {
//            this.strictInsertFill(metaObject, "createId", String.class, getCurrentUserId());
//            this.strictInsertFill(metaObject, "updateId", String.class, getCurrentUserId());
            this.strictInsertFill(metaObject, "createdAt", LocalDateTime.class, LocalDateTime.now());
            this.strictInsertFill(metaObject, "updatedAt", LocalDateTime.class, LocalDateTime.now());
        }

        /**
         * 更新操作
         *
         * @param metaObject
         */
        @Override
        public void updateFill(MetaObject metaObject) {
//            this.strictUpdateFill(metaObject, "updateId", String.class, getCurrentUserId());
            this.strictUpdateFill(metaObject, "updatedAt", LocalDateTime.class, LocalDateTime.now());
        }

        /**
         * 获取当前登录用户ID
         *
         * @return
         */
        private String getCurrentUserId() {

//            SecurityContext sc = SecurityContextHolder.getContext();
//            Authentication auth = sc.getAuthentication();
//            LoginUser user = (LoginUser) auth.getPrincipal();

            return "当前登录用户ID";
        }
    }


